package com.ztgf.order.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ztgf.common.constant.Result;
import com.ztgf.common.utils.DateUtils;
import com.ztgf.order.common.config.YmlConfig;
import com.ztgf.order.mapper.OrderPayRelationMapper;
import com.ztgf.order.models.bo.*;
import com.ztgf.order.models.dto.*;
import com.ztgf.order.models.enums.OrderStateEnum;
import com.ztgf.order.models.service.*;
import com.ztgf.order.models.vo.OrderInfoVO;
import com.ztgf.pay.models.bo.PayOrderMotherSaveBO;
import com.ztgf.pay.models.bo.PayOrderRepaySaveBO;
import com.ztgf.pay.models.bo.PayUserMoneySaveBO;
import com.ztgf.pay.models.service.IPayOrderRepayService;
import com.ztgf.pay.models.service.IPayOrderService;
import com.ztgf.pay.models.service.IPayUserRechargeService;
import com.ztgf.sys.models.service.ISysDictService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

import static com.ztgf.common.utils.UtilConstants.TWO;

/**
 * 订单支付关联关系表控制器
 *
 * @author YUE
 * @Date 2020-06-23 10:34:22
 */
@Slf4j
@DubboService
@Lazy
public class OrderPayRelationServiceImpl extends ServiceImpl<OrderPayRelationMapper, OrderPayRelationDTO> implements IOrderPayRelationService {

    @Resource
    private YmlConfig ymlConfig;

    @Autowired
    private IOrderInfoService orderInfoService;

    @Autowired
    private IOrderStatusService orderStatusService;

    @Autowired
    private IOrderReturnCommodityRefundService orderReturnCommodityRefundService;

    @Autowired
    private IOrderExpirationDateService orderExpirationDateService;

    @Autowired
    private IOrderDeadlineRecordService orderDeadlineRecordService;

    @DubboReference
    private ISysDictService sysDictService;

    @Autowired
    private IOrderProcessLogService orderProcessLogService;

    @DubboReference
    private IPayOrderService payOrderService;

    @DubboReference
    private IPayOrderRepayService payOrderRepayService;

    @Autowired
    private IOrderRepetitionPayService orderRepetitionPayService;

    @DubboReference
    private IPayUserRechargeService PayOrderMotherSaveBO;

    @Autowired
    private IOrderCommodityRelationService orderCommodityRelationService;

    @Autowired
    private IOrderTimeRecordService orderTimeRecordService;


    /**
     * 退款或者支付的信息
     *
     * @param orderPayBO 回调的对象信息
     * @return
     */
    @Override
    public boolean addOrderPayRelationInfo(OrderPayBO orderPayBO) {
        if (null == orderPayBO) {
            log.info("支付回调信息----NULL");
            return false;
        }
        log.info("回调----" + JSON.toJSONString(orderPayBO));
//        if(orderPayBO.getType() == 3){//佣金回调不进行操作，只是更新状态，如果这条记录存在
//            Long orderId = orderPayBO.getOrderId();
//            OrderPayCallBackInfoDTO opCallBackDTO = orderPayCallBackInfoService.getCommissionInfoByOrderId(orderId);
//            if(null == opCallBackDTO){
//                orderPayCallBackInfoService.addByOrderPayBO(orderPayBO);//添加回调信息表
//                return true;
//            }
//            BeanUtils.copyProperties(orderPayBO,opCallBackDTO);
//            orderPayCallBackInfoService.updateById(opCallBackDTO);
//            return true;
//        }

//        orderPayCallBackInfoService.addByOrderPayBO(orderPayBO);//添加回调信息表
        Long orderId = orderPayBO.getOrderId();
        log.info("orderid-------"+orderId+"--------待发货倒计时0----------");
        //获取订单商品关联关系
        List<OrderCommodityRelationDTO> orderCommodityRelationDTOList = orderCommodityRelationService.getByOrderId(orderId);
        Long returnRefundOrderId = orderPayBO.getBusinessOrderWaterId();//业务订单流水id
        if (orderPayBO.getType() == 0) {//返回退款信息（针对取消订单或者售后）
            OrderReturnCommodityRefundDTO orderReturnCommodityRefundDTO = orderReturnCommodityRefundService.selectById(returnRefundOrderId);
            orderReturnCommodityRefundDTO.setRefundStatus(orderPayBO.getRefundStatus());
            orderReturnCommodityRefundDTO.setPayType(orderPayBO.getPayType());
            orderReturnCommodityRefundDTO.setZjBusinessId(orderPayBO.getZjBusinessId());
            orderReturnCommodityRefundDTO.setRefundOrderId(orderPayBO.getRefundOrderId());
            return orderReturnCommodityRefundService.updateById(orderReturnCommodityRefundDTO);
        }
        if (orderPayBO.getType() == 2) {//重复支付信息
            OrderRepetitionPayDTO orderRepetitionPayDTO = orderRepetitionPayService.selectById(returnRefundOrderId);
            orderRepetitionPayDTO.setRefundStatus(orderPayBO.getRefundStatus());
            return orderRepetitionPayService.updateById(orderRepetitionPayDTO);
        }

        if (orderPayBO.getType() == 1) {//返回支付信息
            OrderPayRelationDTO orderPayRelationDTO = selectById(returnRefundOrderId);
            Long currentPayOrderId = orderPayBO.getOrderPayRelationId();//当前支付订单id
            Long payOrderId = orderPayRelationDTO.getPayOrderId();//支付订单id
            if (null != payOrderId) {//重复支付
                //发起退款
                return repeatPay(orderId, orderPayRelationDTO.getRealPayMoney(), currentPayOrderId, returnRefundOrderId, 0);
            }

            orderPayRelationDTO.setPayState(orderPayBO.getPayStatus());
            orderPayRelationDTO.setPayType(orderPayBO.getPayType());
            orderPayRelationDTO.setZjBusinessId(orderPayBO.getZjBusinessId());
            orderPayRelationDTO.setPayOrderId(orderPayBO.getOrderPayRelationId());

            //查询订单状态，如果是取消状态。发起退款（只有预售才会有这个情况）
            OrderStatusDTO orderStatusDTO = orderStatusService.getByOrderId(orderId);
            if (orderStatusDTO.getOrderState() == OrderStateEnum.ORDER_STATE_ENUM_CANCEL.getCode() ||
                    orderStatusDTO.getOrderState() == OrderStateEnum.ORDER_STATE_ENUM_SELLER_CANCEL.getCode()) {//买家取消
                orderPayRelationDTO.setPaySuccessTime(DateUtils.getCurrentDateTime());//支付成功时间
                updateById(orderPayRelationDTO);
                //发起退款
                return refundMoney(orderId, returnRefundOrderId);
            }

            if (orderPayBO.getPayStatus() == OrderStateEnum.ORDER_PAY_STATE_PAY_SUCCESS.getCode()) {//支付成功
                orderPayRelationDTO.setPaySuccessTime(DateUtils.getCurrentDateTime());//支付成功时间
                OrderInfoDTO orderInfoDTO = orderInfoService.selectById(orderId);
                Date currentDateTime = DateUtils.getCurrentDateTime();//当前时间
                int type = orderInfoDTO.getPayType();
                int currentPayPeriods = orderPayRelationDTO.getPeriods();
                if (currentPayPeriods == 2) {//预售付尾款
                    if (orderInfoDTO.getSellPayType() == 1) {//先款交易
//                        orderPayRelationService.payOrderFirstCommission(orderId);//佣金支付
                    }

                    List<Integer> sendList = new ArrayList<Integer>();
                    //处理多个商品中获取发货时间为最少的
                    for(OrderCommodityRelationDTO orderCommodityRelationDTO : orderCommodityRelationDTOList){
                        sendList.add(orderCommodityRelationDTO.getSendDays());
                    }
                    Integer sendDaysNum = Collections.min(sendList);
                    //更新倒计时
                    OrderExpirationDateDTO orderExpirationDateDTO = orderExpirationDateService.getByOrderId(orderId);
                    //SysDictDTO sysDictDTO = sysDictService.getByName(OrderExpireTimeConstant.WAIT_DELIVER_GOODS);//卖家签订合同后倒计时
                    Date expireTime = DateUtils.addDay(currentDateTime, sendDaysNum);//过期时间
                    orderExpirationDateDTO.setExpirationTime(expireTime);
                    orderExpirationDateDTO.setStatus(OrderStateEnum.ORDER_STATE_ENUM_WAIT_DELIVER_GOODS.getCode());

                    String tiem = DateUtils.dateToStr(expireTime);
                    log.info("orderid-------"+orderId+"--------待发货倒计时3----------"+tiem+"---------天数-----"+sendDaysNum);

                    orderExpirationDateService.updateByOrderId(orderExpirationDateDTO);//更新倒计时
                    // 待发货截止时间
                    orderDeadlineRecordService.add(orderId, 5, orderExpirationDateDTO.getExpirationTime());

                    //变为待发货
                    orderStatusDTO.setOrderState(OrderStateEnum.ORDER_STATE_ENUM_WAIT_DELIVER_GOODS.getCode());
                    boolean b = orderStatusService.updateById(orderStatusDTO);
                    if (b) {
                        //添加订单日志表
                        orderProcessLogService.addByOrderInfo(orderId, OrderStateEnum.ORDER_PAY_SUCCESS.getCode());
                    }

                    //发送短信
                    try {
                        orderInfoService.sendMessage(Arrays.asList(orderInfoDTO.getSellShopId()));
                    } catch (Exception e) {
                        log.error("发送短信失败");
                        e.printStackTrace();
                    }
                    //发送站内信
                    try {
                        orderInfoService.sendWebMessageInChangeOrderStatus(orderInfoDTO.getSellShopId(), 2, orderId);
                    } catch (Exception e) {
                        log.error("发送站内信失败");
                        e.printStackTrace();
                    }
                    return updateById(orderPayRelationDTO);
                }

                //新建逻辑
                if(currentPayPeriods == 1){
                    //卖家签订合同
                    if (orderStatusDTO.getContactState() == OrderStateEnum.ORDER_CONTACT_STATE_SELLER_SIGN.getCode()) {

                        if(type == 1 || orderInfoDTO.getSellPayType() == 1){
                            //解冻并支付佣金
                            List<PayUserMoneySaveBO> list = new ArrayList<>();
                            PayUserMoneySaveBO payUserMoneySaveBO = new PayUserMoneySaveBO();
                            payUserMoneySaveBO.setUserId(orderInfoDTO.getSellShopId());
                            payUserMoneySaveBO.setAccountType(1);
                            payUserMoneySaveBO.setMoney(orderPayRelationDTO.getRealPayMoney());
                            payUserMoneySaveBO.setUsage("解冻资金 订单编号：" + orderInfoDTO.getOrderNo());
                            list.add(payUserMoneySaveBO);
                            Result<?> result = PayOrderMotherSaveBO.saveUnfreezeMoney(list);
                            if(result.success()){
                                orderPayRelationDTO.setRealPayMoneyStatus(1);
                            } else {
                                orderPayRelationDTO.setRealPayMoneyStatus(2);
                                log.error("----解冻先款、预售第一笔资金错误----"+JSON.toJSONString(list));
                            }
                            updateById(orderPayRelationDTO);
                        }

                        if (orderInfoDTO.getSellPayType() == 1 && type == 0) {//先款交易现货
//                            orderPayRelationService.payOrderFirstCommission(orderId);//佣金支付
                        }
                    }
                }

                //现货或者预售付收款
                if (type == 0) {//现货

                    //卖家签订合同
                    if (orderStatusDTO.getContactState() == OrderStateEnum.ORDER_CONTACT_STATE_SELLER_SIGN.getCode()) {
                        List<Integer> sendList = new ArrayList<Integer>();
                        //处理多个商品中获取发货时间为最少的
                        for(OrderCommodityRelationDTO orderCommodityRelationDTO : orderCommodityRelationDTOList){
                            sendList.add(orderCommodityRelationDTO.getSendDays());
                        }
                        Integer sendDaysNum = Collections.min(sendList);
                        //更新倒计时
                        OrderExpirationDateDTO orderExpirationDateDTO = orderExpirationDateService.getByOrderId(orderId);
                        //SysDictDTO sysDictDTO = sysDictService.getByName(OrderExpireTimeConstant.WAIT_DELIVER_GOODS);//卖家签订合同后倒计时
                        Date expireTime = DateUtils.addDay(currentDateTime, sendDaysNum);//过期时间
                        orderExpirationDateDTO.setExpirationTime(expireTime);
                        orderExpirationDateDTO.setStatus(OrderStateEnum.ORDER_STATE_ENUM_WAIT_DELIVER_GOODS.getCode());
                        // 待发货截止时间
                        orderDeadlineRecordService.add(orderId, 5, orderExpirationDateDTO.getExpirationTime());
                        String tiem = DateUtils.dateToStr(expireTime);
                        log.info("orderid-------"+orderId+"--------待发货倒计时4----------"+tiem+"---------天数-----"+sendDaysNum);

                        orderExpirationDateService.updateByOrderId(orderExpirationDateDTO);//更新倒计时
                        //添加订单日志表
                        orderProcessLogService.addByOrderInfo(orderId, OrderStateEnum.ORDER_PAY_SUCCESS.getCode());
                        //变为待发货
                        orderStatusDTO.setOrderState(OrderStateEnum.ORDER_STATE_ENUM_WAIT_DELIVER_GOODS.getCode());
                        //发送短信
                        try {
                            orderInfoService.sendMessage(Arrays.asList(orderInfoDTO.getSellShopId()));
                        } catch (Exception e) {
                            log.error("发送短信失败");
                            e.printStackTrace();
                        }
                        //发送站内信
                        try {
                            orderInfoService.sendWebMessageInChangeOrderStatus(orderInfoDTO.getSellShopId(), 2, orderId);
                        } catch (Exception e) {
                            log.error("发送站内信失败");
                            e.printStackTrace();
                        }
                    }
                    //变为生产完成
                    orderStatusDTO.setGoodsProductionState(OrderStateEnum.ORDER_GOODS_PRO_OVER.getCode());
                    orderStatusService.updateById(orderStatusDTO);
                    return updateById(orderPayRelationDTO);
                }
                if (type == 1) {//分批

                    log.info("orderid-------"+orderId+"--------卖家签订合同----------"+orderStatusDTO.getContactState());
                    //变为生产中
                    orderStatusDTO.setGoodsProductionState(OrderStateEnum.ORDER_GOODS_PRO_ING.getCode());
                    //卖家签订合同
                    if (orderStatusDTO.getContactState() == OrderStateEnum.ORDER_CONTACT_STATE_SELLER_SIGN.getCode()) {
                        OrderExpirationDateDTO orderExpirationDateDTO = orderExpirationDateService.getByOrderId(orderId);
                        //处理备货过期倒计时
                        Date stockExpireTime = DateUtils.addDay(currentDateTime, orderCommodityRelationDTOList.get(0).getStockDays());//过期时间
                        orderExpirationDateDTO.setExpirationTime(stockExpireTime);
                        orderStatusDTO.setOrderState(OrderStateEnum.ORDER_STATE_ENUM_WAIT_PAY.getCode());
                        orderExpirationDateDTO.setStatus(OrderStateEnum.ORDER_STATE_ENUM_WAIT_PAY.getCode());
                        orderExpirationDateService.updateByOrderId(orderExpirationDateDTO);//更新过期时间
                        // 记录备货截止时间
                        orderDeadlineRecordService.add(orderId, 9, stockExpireTime);
                        log.info("orderid-------" + orderId + "--------备货倒计时5----------");
                    }
                }
                orderStatusService.updateById(orderStatusDTO);//更新状态
            }
            return updateById(orderPayRelationDTO);
        }
        return true;
    }

    /**
     * 处理重复支付
     *
     * @param orderId
     * @param payMoney
     * @param orderPayId
     * @param waterOrderPayId
     * @param type            0重复支付 1预售取消订单
     * @return
     */
    private boolean repeatPay(Long orderId, BigDecimal payMoney, Long orderPayId, Long waterOrderPayId, int type) {
        OrderInfoDTO orderInfoDTO = orderInfoService.selectById(orderId);
        OrderRepetitionPaySaveBO orderRepetitionPaySaveBO = new OrderRepetitionPaySaveBO();
        orderRepetitionPaySaveBO.setBuyerShopId(orderInfoDTO.getBuyShopId());
        orderRepetitionPaySaveBO.setSellerShopId(orderInfoDTO.getBuyShopId());
        orderRepetitionPaySaveBO.setOrderId(orderId);
        orderRepetitionPaySaveBO.setOrderWatetId(waterOrderPayId);
        orderRepetitionPaySaveBO.setPayOrderId(orderPayId);
        orderRepetitionPaySaveBO.setMoney(payMoney);
        orderRepetitionPaySaveBO.setRefundStatus(1);//退款中
        Long repetitionPayId = orderRepetitionPayService.addAndReturnId(orderRepetitionPaySaveBO);

        int payType = orderInfoDTO.getPayType();
        if (payType == 0) {//现货走退款
            PayOrderRepaySaveBO payOrderRepaySaveBO = new PayOrderRepaySaveBO();
            payOrderRepaySaveBO.setPaymentUserId(orderInfoDTO.getSellShopId());
            payOrderRepaySaveBO.setOriginalOrderId(orderPayId);
            payOrderRepaySaveBO.setBusinessOrderId(orderId);
            payOrderRepaySaveBO.setMoney(payMoney);
            payOrderRepaySaveBO.setUsage("重复支付 订单编号：" + orderInfoDTO.getOrderNo());
            payOrderRepaySaveBO.setNotifyUrl("2");

            OrderPayRelationDTO orderPayRelationDTO = this.selectById(waterOrderPayId);
            Integer moneyPayType = orderPayRelationDTO.getPayType();
            if (moneyPayType == 0) {//余额退款
                payOrderRepayService.saveBalanceOrderRepay(payOrderRepaySaveBO);
                return true;
            }
            //网银退款
            payOrderRepayService.saveOnlineBankOrderRepay(payOrderRepaySaveBO);
            return true;
        }
        List<OrderPayInfoRelationBO> childOrderList = new ArrayList<>();
        OrderPayInfoRelationBO orderPayInfoRelationBO = new OrderPayInfoRelationBO();
        //用于预售相关的信息
        PayOrderMotherSaveBO payOrderMotherSaveBO = new PayOrderMotherSaveBO();
        payOrderMotherSaveBO.setMoney(payMoney);
        payOrderMotherSaveBO.setTrsFlag("B01");
        payOrderMotherSaveBO.setPaymentUserId(orderInfoDTO.getSellShopId());//卖家

        orderPayInfoRelationBO.setPaymentUserId(orderInfoDTO.getSellShopId() + "");
        orderPayInfoRelationBO.setMoney(payMoney);
        orderPayInfoRelationBO.setBusinessOrderNo(orderId + "");
        orderPayInfoRelationBO.setReceiveUserId(orderInfoDTO.getBuyShopId() + "");
        if (type == 0) {
            orderPayInfoRelationBO.setBusinessOrderWaterNo(repetitionPayId + "");
//            payOrderMotherSaveBO.setPayType(3);
            orderPayInfoRelationBO.setMoneyUsage("重复支付 订单编号：" + orderInfoDTO.getOrderNo());
        } else {
//            payOrderMotherSaveBO.setPayType(4);
            orderPayInfoRelationBO.setMoneyUsage("余额-预售退款 订单编号：" + orderInfoDTO.getOrderNo());
        }
        childOrderList.add(orderPayInfoRelationBO);
        String s = JSON.toJSONString(childOrderList);
        payOrderMotherSaveBO.setChildOrderList(s);//设置子订单信息

        //预售走余额支付
        payOrderService.saveBalancePay(payOrderMotherSaveBO);
        return true;
    }

    /**
     * 预售走退款
     *
     * @param orderId
     * @param orderWaterId
     */
    public boolean refundMoney(Long orderId, Long orderWaterId) {
        OrderInfoDTO orderInfoDTO = orderInfoService.selectById(orderId);
        OrderPayRelationDTO orderPayRelationDTO = this.selectById(orderWaterId);
        // 订单支付方式,0全款走余额退款,1分批走余额支付
        Integer payType = orderInfoDTO.getPayType();
        log.info("订单支付方式:{}", payType);
        //创建退款流水记录
        OrderReturnCommodityRefundSaveBO orderReturnCommodityRefundSaveBO = new OrderReturnCommodityRefundSaveBO();
        orderReturnCommodityRefundSaveBO.setOrderId(orderId);
        orderReturnCommodityRefundSaveBO.setPayType(0);//预售只有余额支付
        Long id = orderReturnCommodityRefundService.addAndReturnId(orderReturnCommodityRefundSaveBO);
        //预售的退款(走支付)
        PayOrderMotherSaveBO payOrderMotherSaveBO = new PayOrderMotherSaveBO();
        payOrderMotherSaveBO.setPaymentUserId(orderInfoDTO.getSellShopId());
        payOrderMotherSaveBO.setMoney(orderPayRelationDTO.getRealPayMoney());
//        if(orderInfoDTO.getPayType() == 1 && orderPayRelationDTO.getPeriods() == 1){
//            payOrderMotherSaveBO.setTrsFlag("A00");
//        } else {
//            payOrderMotherSaveBO.setTrsFlag("B01");
//        }

        payOrderMotherSaveBO.setTrsFlag("B01");
//        payOrderMotherSaveBO.setPayType(4);
        List<OrderPayInfoRelationBO> orderPayInfoRelationBOS = new ArrayList<>();
        OrderPayInfoRelationBO orderPayInfoRelationBO = new OrderPayInfoRelationBO();
        orderPayInfoRelationBO.setPaymentUserId(orderInfoDTO.getSellShopId() + "");
        orderPayInfoRelationBO.setMoney(orderPayRelationDTO.getRealPayMoney());
        orderPayInfoRelationBO.setBusinessOrderNo(orderId + "");
        orderPayInfoRelationBO.setBusinessOrderWaterNo(id + "");
        orderPayInfoRelationBO.setReceiveUserId(orderInfoDTO.getBuyShopId() + "");
        orderPayInfoRelationBO.setMoneyUsage("余额-预售取消订单 订单编号：" + orderInfoDTO.getOrderNo());
//        if(orderInfoDTO.getPayType() == 1 && orderPayRelationDTO.getPeriods() == 1){
//            orderPayInfoRelationBO.setTrsFlag("A00");
//        } else {
//            orderPayInfoRelationBO.setTrsFlag("B01");
//        }

        orderPayInfoRelationBO.setTrsFlag("B01");
        orderPayInfoRelationBOS.add(orderPayInfoRelationBO);
        String s = JSON.toJSONString(orderPayInfoRelationBOS);
        payOrderMotherSaveBO.setChildOrderList(s);
        payOrderService.saveBalancePay(payOrderMotherSaveBO);//发起余额支付
        log.info("余额支付");
        // 保存订单时间记录
        OrderTimeRecordSaveBO timeRecordSaveBO = new OrderTimeRecordSaveBO();
        timeRecordSaveBO.setOrderId(orderId);
        timeRecordSaveBO.setOrderState(5);
        orderTimeRecordService.add(timeRecordSaveBO);
        return true;
    }


    /**
     * 根据订单id  计算最后打给卖家的解冻资金
     *
     * @param orderId
     * @return
     */
    public void thawOrderLastMoney(Long orderId) {
        // 查询订单的实付总金额
        OrderInfoDTO orderInfoDTO = orderInfoService.selectById(orderId);
        // 先款不执行后面的操作
        if (orderInfoDTO.getSellPayType().equals(1)) {
            return;
        }
        // 订单的实付总金额
        BigDecimal actualMoney = orderInfoDTO.getActualMoney();
        // 支付的总佣金
        BigDecimal commissionMoney = new BigDecimal("0").setScale(TWO, BigDecimal.ROUND_UP);
        //最后的解冻资金
        BigDecimal lastMoney = actualMoney;
        OrderStatusDTO statusDTO = new OrderStatusDTO();
        statusDTO.setOrderId(orderId);
        statusDTO.setMoneyUnfreezeStatus(1);
        Wrapper<OrderStatusDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("order_id", orderId);
        wrapper.eq("money_unfreeze_status", 0);
        if (orderStatusService.update(statusDTO, wrapper)) {
            //查询所有的订单商品关联信息订单
            List<OrderCommodityRelationDTO> orderCommodityRelationDTOList = orderCommodityRelationService.getByOrderId(orderId);
            // 0全款正常，1分批只解冻最后一批的钱
            if (orderInfoDTO.getPayType().equals(0)) {
                //当前订单 商品 实付
                for (OrderCommodityRelationDTO orderCommodityRelationDTO : orderCommodityRelationDTOList) {
                    BigDecimal actualMoney1 = orderCommodityRelationDTO.getActualMoney();
                    //此笔还剩没退的钱
                    BigDecimal bigDecimal = actualMoney1.subtract(orderCommodityRelationDTO.getReturnCommodityMoney());
                    //每笔要退款的佣金
                    commissionMoney = commissionMoney.add(bigDecimal.multiply(orderCommodityRelationDTO.getCommissionRate()).setScale(TWO, BigDecimal.ROUND_UP));
                    //最后的解冻资金
                    lastMoney = lastMoney.subtract(orderCommodityRelationDTO.getReturnCommodityMoney());
                }
                //减去最后的要支付的佣金
                lastMoney = lastMoney.subtract(commissionMoney);

                List<PayUserMoneySaveBO> list = new ArrayList<>();
                PayUserMoneySaveBO payUserMoneySaveBO = new PayUserMoneySaveBO();
                payUserMoneySaveBO.setUserId(orderInfoDTO.getSellShopId());
                payUserMoneySaveBO.setAccountType(1);
                payUserMoneySaveBO.setMoney(lastMoney);
                payUserMoneySaveBO.setUsage("解冻资金 订单编号：" + orderInfoDTO.getOrderNo());
                list.add(payUserMoneySaveBO);
                Result<?> result = PayOrderMotherSaveBO.saveUnfreezeMoney(list);
                statusDTO = new OrderStatusDTO();
                statusDTO.setOrderId(orderId);
                if (result.success()) {
                    statusDTO.setMoneyUnfreezeStatus(2);
                } else {
                    statusDTO.setMoneyUnfreezeStatus(3);
                }
                wrapper = new EntityWrapper<>();
                wrapper.eq("order_id", orderId);
                wrapper.eq("money_unfreeze_status", 1);
                orderStatusService.update(statusDTO, wrapper);

                //支付佣金
                if(commissionMoney.compareTo(BigDecimal.ZERO) > 0){
                    statusDTO.setOrderId(orderId);
                    statusDTO.setMoneyUnfreezeStatus(1);
                    wrapper = new EntityWrapper<>();
                    wrapper.eq("order_id", orderId);
                    wrapper.eq("commission_money_pay_status", 0);
                    if (orderStatusService.update(statusDTO, wrapper)) {
                        result = payCommission(commissionMoney, orderInfoDTO);//佣金支付
                        statusDTO = new OrderStatusDTO();
                        statusDTO.setOrderId(orderId);
                        if (result.success()) {
                            statusDTO.setCommissionMoneyPayStatus(2);
                        } else {
                            statusDTO.setCommissionMoneyPayStatus(3);
                        }
                        wrapper = new EntityWrapper<>();
                        wrapper.eq("order_id", orderId);
                        wrapper.eq("commission_money_pay_status", 1);
                        orderStatusService.update(statusDTO, wrapper);
                    }
                }
            } else {
                // 查询订单尾款的支付信息
                Wrapper<OrderPayRelationDTO> dtoWrapper = new EntityWrapper<>();
                dtoWrapper.eq("order_id", orderInfoDTO.getId());
                dtoWrapper.eq("periods", 2);
                dtoWrapper.eq("pay_state", 2);
                OrderPayRelationDTO orderPayRelationDTO = this.selectOne(dtoWrapper);
                // 冻结的金额=尾款的实付金额
                lastMoney = orderPayRelationDTO.getRealPayMoney();
                //当前订单 商品 实付
                for (OrderCommodityRelationDTO orderCommodityRelationDTO : orderCommodityRelationDTOList) {
                    BigDecimal actualMoney1 = orderCommodityRelationDTO.getActualMoney();
                    //此笔还剩没退的钱
                    BigDecimal bigDecimal = actualMoney1.subtract(orderCommodityRelationDTO.getReturnCommodityMoney());
                    //每笔要退款的佣金
                    commissionMoney = commissionMoney.add(bigDecimal.multiply(orderCommodityRelationDTO.getCommissionRate()).setScale(TWO, BigDecimal.ROUND_UP));
                    //最后的解冻资金
                    lastMoney = lastMoney.subtract(orderCommodityRelationDTO.getReturnCommodityMoney());
                }

                if(lastMoney.compareTo(BigDecimal.ZERO) > 0){//未退完
                    //解冻剩余余额
                    if(lastMoney.subtract(commissionMoney).compareTo(BigDecimal.ZERO) >= 0){
                        //减去最后的要支付的佣金
                        lastMoney = lastMoney.subtract(commissionMoney);
                        List<PayUserMoneySaveBO> list = new ArrayList<>();
                        PayUserMoneySaveBO payUserMoneySaveBO = new PayUserMoneySaveBO();
                        payUserMoneySaveBO.setUserId(orderInfoDTO.getSellShopId());
                        payUserMoneySaveBO.setAccountType(1);
                        payUserMoneySaveBO.setMoney(lastMoney);
                        payUserMoneySaveBO.setUsage("解冻资金 订单编号：" + orderInfoDTO.getOrderNo());
                        list.add(payUserMoneySaveBO);
                        Result<?> result = PayOrderMotherSaveBO.saveUnfreezeMoney(list);
                        statusDTO = new OrderStatusDTO();
                        statusDTO.setOrderId(orderId);
                        if (result.success()) {
                            statusDTO.setMoneyUnfreezeStatus(2);
                        } else {
                            statusDTO.setMoneyUnfreezeStatus(3);
                        }
                        wrapper = new EntityWrapper<>();
                        wrapper.eq("order_id", orderId);
                        wrapper.eq("money_unfreeze_status", 1);
                        orderStatusService.update(statusDTO, wrapper);

                        //支付佣金
                        if(commissionMoney.compareTo(BigDecimal.ZERO) > 0){
                            statusDTO.setOrderId(orderId);
                            statusDTO.setMoneyUnfreezeStatus(1);
                            wrapper = new EntityWrapper<>();
                            wrapper.eq("order_id", orderId);
                            wrapper.eq("commission_money_pay_status", 0);
                            if (orderStatusService.update(statusDTO, wrapper)) {
                                result = payCommission(commissionMoney, orderInfoDTO);//佣金支付
                                statusDTO = new OrderStatusDTO();
                                statusDTO.setOrderId(orderId);
                                if (result.success()) {
                                    statusDTO.setCommissionMoneyPayStatus(2);
                                } else {
                                    statusDTO.setCommissionMoneyPayStatus(3);
                                }
                                wrapper = new EntityWrapper<>();
                                wrapper.eq("order_id", orderId);
                                wrapper.eq("commission_money_pay_status", 1);
                                orderStatusService.update(statusDTO, wrapper);
                            }
                        }
                    } else {

                        //解冻剩余余额
                        List<PayUserMoneySaveBO> list = new ArrayList<>();
                        PayUserMoneySaveBO payUserMoneySaveBO = new PayUserMoneySaveBO();
                        payUserMoneySaveBO.setUserId(orderInfoDTO.getSellShopId());
                        payUserMoneySaveBO.setAccountType(1);
                        payUserMoneySaveBO.setMoney(lastMoney);
                        payUserMoneySaveBO.setUsage("解冻资金 订单编号：" + orderInfoDTO.getOrderNo());
                        list.add(payUserMoneySaveBO);
                        Result<?> result = PayOrderMotherSaveBO.saveUnfreezeMoney(list);
                        statusDTO = new OrderStatusDTO();
                        statusDTO.setOrderId(orderId);
                        if (result.success()) {
                            statusDTO.setMoneyUnfreezeStatus(2);
                        } else {
                            statusDTO.setMoneyUnfreezeStatus(3);
                        }
                        wrapper = new EntityWrapper<>();
                        wrapper.eq("order_id", orderId);
                        wrapper.eq("money_unfreeze_status", 1);
                        orderStatusService.update(statusDTO, wrapper);

                        //用余额支付佣金
                        if(commissionMoney.compareTo(BigDecimal.ZERO) > 0){
                            statusDTO.setOrderId(orderId);
                            statusDTO.setMoneyUnfreezeStatus(1);
                            wrapper = new EntityWrapper<>();
                            wrapper.eq("order_id", orderId);
                            wrapper.eq("commission_money_pay_status", 0);
                            if (orderStatusService.update(statusDTO, wrapper)) {
                                result = payCommission(commissionMoney, orderInfoDTO, true);//佣金支付
                                statusDTO = new OrderStatusDTO();
                                statusDTO.setOrderId(orderId);
                                if (result.success()) {
                                    statusDTO.setCommissionMoneyPayStatus(2);
                                } else {
                                    statusDTO.setCommissionMoneyPayStatus(3);
                                }
                                wrapper = new EntityWrapper<>();
                                wrapper.eq("order_id", orderId);
                                wrapper.eq("commission_money_pay_status", 1);
                                orderStatusService.update(statusDTO, wrapper);
                            }
                        }
                    }

                } else {//已退完
                    //支付佣金
                    if(commissionMoney.compareTo(BigDecimal.ZERO) > 0){
                        statusDTO = new OrderStatusDTO();
                        statusDTO.setOrderId(orderId);
                        statusDTO.setMoneyUnfreezeStatus(1);
                        wrapper = new EntityWrapper<>();
                        wrapper.eq("order_id", orderId);
                        wrapper.eq("commission_money_pay_status", 0);
                        if (orderStatusService.update(statusDTO, wrapper)) {
                            Result result = payCommission(commissionMoney, orderInfoDTO, true);//佣金支付
                            statusDTO = new OrderStatusDTO();
                            statusDTO.setOrderId(orderId);
                            if (result.success()) {
                                statusDTO.setCommissionMoneyPayStatus(2);
                            } else {
                                statusDTO.setCommissionMoneyPayStatus(3);
                            }
                            wrapper = new EntityWrapper<>();
                            wrapper.eq("order_id", orderId);
                            wrapper.eq("commission_money_pay_status", 1);
                            orderStatusService.update(statusDTO, wrapper);
                        }
                    }
                }

            }

        }

    }

    /**
     * 佣金支付
     *
     * @param commissionMoney
     * @return
     */
    public Result payCommission(BigDecimal commissionMoney, OrderInfoDTO orderInfoDTO){
        return payCommission(commissionMoney, orderInfoDTO, false);
    }

    /**
     * 佣金支付
     *
     * @param commissionMoney
     * @return
     */
    public Result payCommission(BigDecimal commissionMoney, OrderInfoDTO orderInfoDTO, boolean isA00) {
        commissionMoney.setScale(TWO, BigDecimal.ROUND_UP);
        List<OrderPayInfoRelationBO> childOrderList = new ArrayList<>();
        OrderPayInfoRelationBO orderPayInfoRelationBO = new OrderPayInfoRelationBO();
        PayOrderMotherSaveBO payOrderMotherSaveBO = new PayOrderMotherSaveBO();

        orderPayInfoRelationBO.setPaymentUserId(orderInfoDTO.getSellShopId() + "");
        orderPayInfoRelationBO.setMoney(commissionMoney);
        orderPayInfoRelationBO.setBusinessOrderNo(orderInfoDTO.getId() + "");
        orderPayInfoRelationBO.setBusinessOrderWaterNo(orderInfoDTO.getId() + "");
        orderPayInfoRelationBO.setReceiveUserId(orderInfoDTO.getBuyShopId() + "");
        orderPayInfoRelationBO.setMoneyUsage("佣金支付 订单编号：" + orderInfoDTO.getOrderNo());
        childOrderList.add(orderPayInfoRelationBO);
        String s = JSON.toJSONString(childOrderList);

        payOrderMotherSaveBO.setPaymentUserId(orderInfoDTO.getSellShopId());
        payOrderMotherSaveBO.setMoney(commissionMoney);
        if(isA00){
            payOrderMotherSaveBO.setTrsFlag("A00");
        } else {
            payOrderMotherSaveBO.setTrsFlag("B01");
        }

//        payOrderMotherSaveBO.setPayType(1);//佣金支付
        payOrderMotherSaveBO.setChildOrderList(s);

        orderInfoDTO.setLastCommissionMoney(commissionMoney);
        orderInfoService.updateById(orderInfoDTO);//更新最后的佣金

        Result result = payOrderService.saveBalancePay(payOrderMotherSaveBO);//佣金支付
//        OrderPayCallBackInfoDTO opCallBackDTO = orderPayCallBackInfoService.getCommissionInfoByOrderId(orderInfoDTO.getId());
//        OrderPayBO orderPayBO = new OrderPayBO();
//        orderPayBO.setOrderId(orderInfoDTO.getId());
//        orderPayBO.setOrderNo(orderInfoDTO.getOrderNo());
//        orderPayBO.setType(3);
//        orderPayBO.setPayType(0);
//        orderPayBO.setCommissionMoney(commissionMoney);
//        if (result.getCode() == CodeEnum.SUCCESS.getCode()) {//返回成功
//            if (null == opCallBackDTO) {//不存在添加
//                orderPayBO.setPayStatus(2);
//                orderPayCallBackInfoService.addByOrderPayBO(orderPayBO);//添加回调信息表
//            } else {//存在更新
//                opCallBackDTO.setPayStatus(2);
//                orderPayCallBackInfoService.updateById(opCallBackDTO);
//            }
//        } else {//返回失败
//            if (null == opCallBackDTO) {//不存在添加
//                orderPayBO.setPayStatus(3);
//                orderPayCallBackInfoService.addByOrderPayBO(orderPayBO);//添加回调信息表
//            } else {//存在更新
//                opCallBackDTO.setPayStatus(3);
//                orderPayCallBackInfoService.updateById(opCallBackDTO);
//            }
//        }
        return result;
    }

    /**
     * 佣金支付（先款订单）
     *
     * @param orderId 订单id
     * @return
     */
    public Result payOrderFirstCommission(Long orderId) {
        //查询所有的订单商品关联信息订单
        List<OrderCommodityRelationDTO> orderCommodityRelationDTOList = orderCommodityRelationService.getByOrderId(orderId);

        BigDecimal commissionMoney = new BigDecimal("0").setScale(TWO, BigDecimal.ROUND_UP);//支付的总佣金
        for (OrderCommodityRelationDTO orderCommodityRelationDTO : orderCommodityRelationDTOList) {
            BigDecimal actualMoney1 = orderCommodityRelationDTO.getActualMoney();//当前订单 商品 实付
            BigDecimal bigDecimal = actualMoney1.subtract(orderCommodityRelationDTO.getReturnCommodityMoney());//此笔还剩没退的钱
            commissionMoney = commissionMoney.add(bigDecimal.multiply(orderCommodityRelationDTO.getCommissionRate()).setScale(TWO, BigDecimal.ROUND_UP));//每笔要退款的佣金
        }
        if (commissionMoney.compareTo(new BigDecimal("0")) == 0) {//佣金为0不调用
            return new Result();
        }
        commissionMoney.setScale(TWO, BigDecimal.ROUND_UP);

        List<OrderPayInfoRelationBO> childOrderList = new ArrayList<>();
        OrderPayInfoRelationBO orderPayInfoRelationBO = new OrderPayInfoRelationBO();
        PayOrderMotherSaveBO payOrderMotherSaveBO = new PayOrderMotherSaveBO();

        OrderInfoDTO orderInfoDTO = orderInfoService.selectById(orderId);
        orderPayInfoRelationBO.setPaymentUserId(orderInfoDTO.getSellShopId() + "");
        orderPayInfoRelationBO.setMoney(commissionMoney);
        orderPayInfoRelationBO.setBusinessOrderNo(orderInfoDTO.getId() + "");
        orderPayInfoRelationBO.setBusinessOrderWaterNo(orderInfoDTO.getId() + "");
        orderPayInfoRelationBO.setReceiveUserId(orderInfoDTO.getBuyShopId() + "");
        orderPayInfoRelationBO.setMoneyUsage("佣金支付 订单编号：" + orderInfoDTO.getOrderNo());
        orderPayInfoRelationBO.setTrsFlag("A00");
        childOrderList.add(orderPayInfoRelationBO);
        String s = JSON.toJSONString(childOrderList);

        payOrderMotherSaveBO.setPaymentUserId(orderInfoDTO.getSellShopId());
        payOrderMotherSaveBO.setMoney(commissionMoney);
        //payOrderMotherSaveBO.setTrsFlag("A00");
//        payOrderMotherSaveBO.setPayType(1);//佣金支付
        payOrderMotherSaveBO.setChildOrderList(s);

        orderInfoDTO.setLastCommissionMoney(commissionMoney);
        orderInfoService.updateById(orderInfoDTO);//更新最后的佣金

        Result result = payOrderService.saveBalancePay(payOrderMotherSaveBO);//佣金支付

//        OrderPayCallBackInfoDTO opCallBackDTO = orderPayCallBackInfoService.getCommissionInfoByOrderId(orderInfoDTO.getId());
//        OrderPayBO orderPayBO = new OrderPayBO();
//        orderPayBO.setOrderId(orderInfoDTO.getId());
//        orderPayBO.setOrderNo(orderInfoDTO.getOrderNo());
//        orderPayBO.setType(3);
//        orderPayBO.setCommissionMoney(commissionMoney);
//        if (result.getCode() == CodeEnum.SUCCESS.getCode()) {//返回成功
//            if (null == opCallBackDTO) {//不存在添加
//                orderPayBO.setPayStatus(2);
//                orderPayCallBackInfoService.addByOrderPayBO(orderPayBO);//添加回调信息表
//            } else {//存在更新
//                opCallBackDTO.setPayStatus(2);
//                orderPayCallBackInfoService.updateById(opCallBackDTO);
//            }
//        } else {//返回失败
//            if (null == opCallBackDTO) {//不存在添加
//                orderPayBO.setPayStatus(3);
//                orderPayCallBackInfoService.addByOrderPayBO(orderPayBO);//添加回调信息表
//            } else {//存在更新
//                opCallBackDTO.setPayStatus(3);
//                orderPayCallBackInfoService.updateById(opCallBackDTO);
//            }
//        }
        return result;
    }

    @Override
    public boolean add(OrderPayRelationSaveBO saveBO) {
        OrderPayRelationDTO dto = new OrderPayRelationDTO();
        BeanUtils.copyProperties(saveBO, dto);
        Long id = ymlConfig.getPkId();
        dto.setId(id);
        return this.insert(dto);
    }

    /**
     * 初始化订单 添加 订单支付表
     *
     * @param orderInfoVO
     * @return
     */
    public boolean addByOrderInfo(OrderInfoVO orderInfoVO) {
        OrderInfoDTO infodto = new OrderInfoDTO();//订单信息表对象
        infodto.setId(orderInfoVO.getId());
        OrderPayRelationDTO dto = new OrderPayRelationDTO();
        dto.setOrderId(orderInfoVO.getId());
        dto.setPayState(0);
        BigDecimal actualMoney = new BigDecimal(0);
//        if(null !=orderInfoVO.getPurchaseOrderType() && orderInfoVO.getPurchaseOrderType() == BargainStateEnum.PURCHASE_ORDER_TYPE.getCode()){//询盘订单扣除服务费
//             actualMoney = orderInfoVO.getActualMoney().subtract(orderInfoVO.getPurchaseFeeMoneyScalePrice());//总实付金额(实付总额减去服务费)
//        }else{
//             actualMoney = orderInfoVO.getActualMoney();//总实付金额
//        }
        actualMoney = orderInfoVO.getActualMoney();//总实付金额
        BigDecimal commissionMoney = orderInfoVO.getCommissionMoney();//总分润
        if (orderInfoVO.getPayType() == 1) {//预售订单 单商品
            Integer firstBalance = orderInfoVO.getOrderCommodityDetailVOList().get(0).getFirstBalance();//首款比例
            Integer tailBalance = orderInfoVO.getOrderCommodityDetailVOList().get(0).getTailBalance();//尾款比例
            BigDecimal firstActualMoney = actualMoney.multiply(new BigDecimal(firstBalance).divide(new BigDecimal(100))).setScale(2, BigDecimal.ROUND_UP);;//首款
            //BigDecimal tailActualMoney = actualMoney.multiply(new BigDecimal(tailBalance).divide(new BigDecimal(100)));//尾款
            BigDecimal tailActualMoney = actualMoney.subtract(firstActualMoney);//尾款
            BigDecimal firstCommission = commissionMoney.multiply(new BigDecimal(firstBalance).divide(new BigDecimal(100))).setScale(2, BigDecimal.ROUND_UP);;//首款分润
            //BigDecimal tailCommission = commissionMoney.multiply(new BigDecimal(tailBalance).divide(new BigDecimal(100)));//尾款分润
            BigDecimal tailCommission = commissionMoney.subtract(firstCommission);//尾款分润

            for (int i = 0; i < 2; i++) {
                Long id = ymlConfig.getPkId();
                dto.setId(id);
                if (i == 1) {//首款
                    dto.setRealPayMoney(firstActualMoney);
                    dto.setCommissionMoney(firstCommission);
                    dto.setPeriods(1);//一期
                } else {//尾款
                    dto.setRealPayMoney(tailActualMoney);
                    dto.setCommissionMoney(tailCommission);
                    dto.setPeriods(2);//二期
                    if(orderInfoVO.getSellPayType() == 1){//先款交易
                        infodto.setLastCommissionMoney(firstCommission.add(tailCommission));
                        orderInfoService.updateById(infodto);//预售更新订单表实付佣金
                    }
                }
                this.insert(dto);
            }
            return true;
        }


        Long id = ymlConfig.getPkId();
        dto.setRealPayMoney(actualMoney);
        dto.setCommissionMoney(commissionMoney);
        dto.setId(id);
        dto.setPeriods(1);
        if(orderInfoVO.getSellPayType() == 1) {//先款交易
            infodto.setLastCommissionMoney(commissionMoney);
            orderInfoService.updateById(infodto);//现货更新订单表实付佣金
        }
        return this.insert(dto);
    }

    @Override
    public boolean getOrderAllPaySuccess(Long orderId, Long id) {
        boolean paySuccess = true;
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("order_id", orderId);
        wrapper.in("pay_state", "0,1,3");
        List<OrderPayRelationDTO> relationDTOList = this.selectList(wrapper);
        if(relationDTOList != null && relationDTOList.size() > 0){
            for(OrderPayRelationDTO relationDTO : relationDTOList){
                if(id != null && relationDTO.getId().equals(id)){
                    continue;
                }
                if(relationDTO.getPayState() == 0 || relationDTO.getPayState() == 1 || relationDTO.getPayState() == 3){
                    paySuccess = false;
                    break;
                }
            }
        }

        return paySuccess;
    }

    /**
     * 获取订单期数 根据订单id
     *
     * @param orderId 订单id
     * @param periods 期数
     * @return
     */
    public OrderPayRelationDTO getByOrderIdAndPeriods(Long orderId, int periods) {
        Wrapper<OrderPayRelationDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("order_id", orderId);
        wrapper.eq("periods", periods);
        return selectOne(wrapper);
    }

    /**
     * 获取订单期数排序 根据订单id
     *
     * @param orderId 订单id
     * @return
     */
    public List<OrderPayRelationDTO> getByOrderId(Long orderId) {
        Wrapper<OrderPayRelationDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("order_id", orderId);
        wrapper.orderBy("periods", true);
        return selectList(wrapper);
    }

    /**
     * 根据订单id获取
     *
     * @param orderId
     * @return
     */
    public List<OrderPayRelationDTO> getListByOrderId(Long orderId) {
        Wrapper<OrderPayRelationDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("order_id", orderId);
        wrapper.orderBy("create_time");
        return selectList(wrapper);
    }
}
